package com.tyk.demo.controller;

import com.sun.deploy.net.HttpResponse;
import com.tyk.demo.utils.FTPFileUploadUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;

@Controller
public class UploadController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UploadController.class);

    @GetMapping("/upload")
    public String upload() {
        return "upload";
    }

    @PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return "文件上传失败，请重新上传";
        }
        String fileName = file.getOriginalFilename();
        String filePath = "E:\\Project\\file\\";
        File dest = new File(filePath + fileName);
        dest.createNewFile();
        try {
            file.transferTo(dest);
            LOGGER.info("上传成功！");
            return "上传成功！";
        } catch (IOException e) {
            LOGGER.error(e.toString(),e);
        }
        return "上传失败！";
    }

    @PostMapping("/multiUpload")
    @ResponseBody
    public String multiUpload(@RequestParam("file") List<MultipartFile> files) throws IOException {
        for (int i = 0; i < files.size(); i++) {
            MultipartFile file = files.get(i);
            if (file.isEmpty()) {
                return "第"+(i+1)+"个文件上传失败，请重新上传";
            }
            String fileName = file.getOriginalFilename();
            String filePath = "E:\\Project\\file\\";
            File dest = new File(filePath + fileName);
            try {
//                dest.createNewFile();
                file.transferTo(dest);
                LOGGER.info("第{}个文件上传成功",(i+1));
            } catch (IOException e) {
                LOGGER.error(e.toString(),e);
                return "第"+(i+1)+"个文件上传失败，请重新上传";
            }
        }
        return "上传成功";
    }

    @PostMapping("/updateAvater")
    @ResponseBody
    public String updateAvater(MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return "文件上传失败，请重新上传！";
            }
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String fileName = UUID.randomUUID().toString().replace("-", "") + suffix;
            InputStream inputStream = file.getInputStream();
            Boolean flag = FTPFileUploadUtils.uploadFile(fileName, inputStream);
            if (flag) {
                LOGGER.info("上传成功！");
                return "上传成功！";
            }
        } catch (IOException e) {
            LOGGER.error(e.toString(),e);
            return "上传异常！";
        }
        return "上传成功！";
    }

    @RequestMapping("/downloadFile")
    public void downloadFileFromFTP(@RequestParam("fileName") String fileName, HttpServletResponse response) throws IOException {
        fileName = "72902c113ab74792950ecfc79c40e7f5.png";
//        response.setHeader("Accept-Ranges", "bytes");
//        response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName));
        response.reset();
//        response.setContentType("bin");
        response.setContentType("application/octet-stream");
//        response.addHeader("Content-Didposition","attachment;filename=\\"+fileName+"\\");
        response.setHeader("Content-Disposition", "attachment;filename=" + "who (2).png" );

        InputStream inputStream = FTPFileUploadUtils.downloadFile(fileName);
        try(BufferedInputStream bis = new BufferedInputStream(inputStream);) {
            byte[] buff = new byte[1024];
            OutputStream os  = response.getOutputStream();
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
            LOGGER.info("本地文件下载成功！！！");
        } catch (IOException e) {
            LOGGER.error("{}",e);
//            return "下载失败";
            LOGGER.info("本地文件下载失败！！！");
        }
    }
    @RequestMapping("/downloadFileLocal")
    public void downloadFileLocal(HttpServletResponse response) throws FileNotFoundException {
        String fileName = "who (2).png";
        InputStream inputStream = new FileInputStream("E:\\Project\\file\\who (2).png");
        // 设置输出格式
        response.reset();
//        response.setContentType("bin");
        response.setContentType("application/octet-stream");
//        response.addHeader("Content-Didposition","attachment;filename=\\"+fileName+"\\");
        response.setHeader("Content-Disposition", "attachment;filename=" + "who (2).png" );

        byte[] bytes = new byte[100];
        int len;
        try {
            while ((len = inputStream.read(bytes)) > 0) {
                response.getOutputStream().write(bytes,0,len);
            }
            inputStream.close();
            LOGGER.info("本地文件下载成功！！！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("/download2")
    public void fileDownLoad(HttpServletResponse response, @RequestParam("fileName") String fileName){
        File file = new File("E:\\Project\\file\\who (2).png");
        if(!file.exists()){
//            return "下载文件不存在";
        }
        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment;filename=" + "who (2).png" );

        try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));) {
            byte[] buff = new byte[1024];
            OutputStream os  = response.getOutputStream();
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
            LOGGER.info("本地文件下载成功！！！");
        } catch (IOException e) {
            LOGGER.error("{}",e);
//            return "下载失败";
            LOGGER.info("本地文件下载失败！！！");
        }
//        return "下载成功";
    }
}
